package com.base.controller.wx_mp_api;

import com.base.helper.WebHelper;
import com.base.po.param.NetState;
import com.base.po.voip.Subscribers;
import com.base.po.voip.UsersConfig;
import com.base.po.wx.WXCgiBinUserInfo;
import com.base.service.SubscribersService;
import com.base.service.UsersConfigService;
import com.base.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * 微信接口
 *
 * @author K.
 */
@Slf4j
@Controller
@RequestMapping("/weixin")
public class Wx_MpController {

    private final UsersService usersService;

    private final SubscribersService subscribersService;

    private final UsersConfigService usersConfigService;

    private final Wx_TokenController wx_tokenController;

    public Wx_MpController(UsersService usersService, SubscribersService subscribersService, UsersConfigService usersConfigService, Wx_TokenController wx_tokenController) {
        this.usersService = usersService;
        this.subscribersService = subscribersService;
        this.usersConfigService = usersConfigService;
        this.wx_tokenController = wx_tokenController;
    }

    /**
     * 微信 - 用户授权
     */
    @RequestMapping(value = "/authorize", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState authorize(HttpServletRequest request, String parentId, String code) throws Exception {
        NetState netState = new NetState();
        log.warn("[微信JSAPI]parentId={},code={}",parentId,code);
        if (parentId == null || parentId.equals("") || code == null || code.equals("")){
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("参数异常");
            return netState;
        }

        // 用户
        Subscribers sub = null;
        // 代理商
        UsersConfig config = null;
        String appId = null;
        String secret = null;
        String qrCode = null;
        try {
            config = usersConfigService.selectByParentId(parentId);
            appId = config.getWxMpAppid();
            secret = config.getWxMpAppsecret();
            qrCode = config.getWxMpQRCode();
        }catch (Exception e){
            netState.setErrorCode(NetState.NODATA);
            netState.setData("数据异常");
            return netState;
        }

        try {
            Map<String, Object> accessTokenMap = wx_tokenController.getAccessTokenByOauth2(appId, secret, code);
            String openId = (String)accessTokenMap.get("openId");
            String accessToken = wx_tokenController.getTokeFromRedis(appId, secret);
            if (accessToken != null && !accessToken.equals("") && openId != null && !openId.equals("")){
                Map<String, Object> userInfoMap = this.getUserInfo(accessToken, openId);
                Integer subscribe = (Integer)userInfoMap.get("subscribe");
                openId = (String)userInfoMap.get("openId");

                if (subscribe != null && !subscribe.equals("") && openId != null && !openId.equals("")){
                    userInfoMap.put("parentId", parentId);
                    userInfoMap.put("wxQRCode", qrCode);
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    log.warn("[微信JSAPI]获取openID={}",userInfoMap.toString());
                    netState.setData("授权成功");
                    netState.setJson(userInfoMap);
                }else {
                    netState.setErrorCode(NetState.ERROR_OPERATE);
                    netState.setData("授权失败,无效openId");
                    log.warn("[微信JSAPI]授权失败,无效openId");
                }
            }else {
                netState.setErrorCode(NetState.ERROR_OPERATE);
                netState.setData("授权失败,无效accessToken");
                log.warn("[微信JSAPI]授权失败,无效accessToken");
            }
        }catch (Exception e){
            e.printStackTrace();
            netState.setErrorCode(NetState.SYSTEM_ERROR);
            netState.setData("授权异常,无效code");
            log.warn("[微信JSAPI]授权异常,无效code");
        }
        return netState;
    }

    public Map<String, Object> getUserInfo(String accessToken, String openId){
        Map<String, Object> map = new HashedMap();

        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        try {
            String result = WebHelper.PostData(tokenUrl, null, null, null);
            WXCgiBinUserInfo userInfo = (WXCgiBinUserInfo) JSONObject.toBean(JSONObject.fromObject(result), WXCgiBinUserInfo.class);
            map.put("openId", userInfo.getOpenid());
            map.put("unionId", userInfo.getUnionid());
            map.put("subscribe", userInfo.getSubscribe());
        }catch (Exception e){
            e.printStackTrace();
            map = null;
        }

        return map;
    }

//    public Map<String, Object> getUserInfo(String accessToken, String openId){
//        Map<String, Object> map = new HashedMap();
//
//        String tokenUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
//        try {
//            String result = WebHelper.PostData(tokenUrl, null, null, null);
//            WXUserInfo userInfo = (WXUserInfo) JSONObject.toBean(JSONObject.fromObject(result), WXUserInfo.class);
//            map.put("nickname", userInfo.getNickname());
//            map.put("imgUrl", userInfo.getHeadimgurl());
//            map.put("openId", userInfo.getOpenid());
//            map.put("unionId", userInfo.getUnionid());
//        }catch (Exception e){
//            map = null;
//        }
//
//        return map;
//    }
}
